import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ResData, Status } from 'src/response/res-data.interface';
import { Connection, Repository } from 'typeorm';
import { CreateCustomFormSubmitDto } from './dto/create-custom-form-submit.dto';
import { UpdateCustomFormSubmitDto } from './dto/update-custom-form-submit.dto';
import { CustomFormSubmit } from './entities/custom-form-submit.entity';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class CustomFormSubmitService {
  constructor(@InjectRepository(CustomFormSubmit) private customFormSubmitRepository: Repository<CustomFormSubmit>, private connection: Connection) { }

  async create(createCustomFormSubmitDto: any) {
    let resdata: ResData;
    try {
      const result = await this.customFormSubmitRepository.save(createCustomFormSubmitDto);
      const inStorageData = createCustomFormSubmitDto.inStorageData;
      if (createCustomFormSubmitDto.id) {
        this.deleteInStorageData(inStorageData, createCustomFormSubmitDto.id)
      }
      this.inStorage(inStorageData, result.id);
      resdata = {
        code: Status.SUCCESS,
        msg: '保存成功',
        content: result
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  // 表单入库内容更新时删除数据库已有内容
  deleteInStorageData(inStorageData: any, submitId: string) {
    const queryRunner = this.connection.createQueryRunner();
    const sqlArr = [];
    for (let table in inStorageData) {
      let sql = `delete from ${table} where submitid='${submitId}'`
      sqlArr.push(sql);
    }
    sqlArr.forEach(async (sql) => {
      await queryRunner.query(sql)
    })
  }

  // 入库操作
  inStorage(inStorageData: any, submitId: string) {
    const sqlArr = [];
    for (let table in inStorageData) {
      let sql = `insert into ${table} (`
      sql += `id,`
      for (let field in inStorageData[table] as any) {
        sql += field;
        sql += ','
      }
      sql += `submitId`
      sql += ') values (';
      sql += `'${uuidv4()}',`
      for (let field in inStorageData[table] as any) {
        sql += `'${inStorageData[table][field]}'`;
        sql += ','
      }
      sql += `'${submitId}'`;
      sql += ');'
      sqlArr.push(sql);
    }
    const queryRunner = this.connection.createQueryRunner();
    sqlArr.forEach(async (sql) => {
      await queryRunner.query(sql)
    })
  }

  async findAll(querys) {
    let resdata: ResData;
    try {
      const { startTime, endTime } = querys;
      let sql = this.customFormSubmitRepository.createQueryBuilder("customFormSubmit");
      if (startTime) {
        sql.andWhere('customFormSubmit.createdDate between :startTime and :endTime', { startTime, endTime })
      }
      sql.skip(querys.skip).take(querys.take).orderBy("updatedDate", "DESC")
      const result = await sql.getManyAndCount()
      const [list, total] = result;
      resdata = {
        code: Status.SUCCESS,
        msg: '查询成功',
        content: { result: list, total }
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async findOne(id: string) {
    let resdata: ResData;
    try {
      const result = await this.customFormSubmitRepository.findOne(id);
      resdata = {
        code: Status.SUCCESS,
        msg: '查询成功',
        content: result
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async update(id: string, updateCustomFormSubmitDto: UpdateCustomFormSubmitDto) {
    let resdata: ResData;
    try {
      const result = await this.customFormSubmitRepository.update(id, updateCustomFormSubmitDto);
      resdata = {
        code: Status.SUCCESS,
        msg: '更新成功',
        content: result
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }

  async remove(id: string) {
    let resdata: ResData;
    try {
      const result = await this.customFormSubmitRepository.delete(id);
      resdata = {
        code: Status.SUCCESS,
        msg: '删除成功',
        content: result
      };
      return resdata;
    } catch (e) {
      resdata = {
        code: Status.ERROR,
        msg: e,
      };
      return resdata;
    }
  }
}
